package com.xyauto.theme.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.xyauto.theme.R
import com.xyauto.theme.base.BaseListActivity
import com.xyauto.theme.bean.IThemeBean
import com.xyauto.theme.fragment.ThemeListAdapter
import com.xyauto.theme.utils.startDetails
import com.xyauto.theme.utils.toHome
import com.xyauto.theme.vm.MainListViewModel


@SuppressLint("NotifyDataSetChanged")
class LocalActivity : BaseListActivity<ThemeListAdapter, IThemeBean, MainListViewModel>() {

    companion object {
        const val SELECT_FLAG_KEY = "com.xyauto.theme.activity.LocalActivity.selectFlag"
    }

    private var selectFlag: String? = null

    override fun getLayoutId(): Int = R.layout.activity_local_list


    override fun newLayoutManager(context: Context) = GridLayoutManager(context, 3, RecyclerView.VERTICAL, false)

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        loadSelectFlag(intent)
        onRefresh()
    }

    override fun initData() {
        loadSelectFlag(intent)
        viewModel.clearObserver.observe(this) {
            selectFlag = null
            toHome()
        }
        viewModel.listData.observe(this) {
            onSuccessList(it, false)
            selectFlag?.let { key ->
                viewModel.onApply(this, it.find { item ->
                    TextUtils.equals(item.getName(), key)
                })
            }
        }
        onRefresh()
    }

    private fun loadSelectFlag(intent: Intent?){
        selectFlag = intent?.let {
            if (it.hasExtra(SELECT_FLAG_KEY)) {
                it.getStringExtra(SELECT_FLAG_KEY)
            } else {
                null
            }
        }
    }


    override fun onLoadData(isRefresh: Boolean, pagerNumber: Int) {
        viewModel.getLocalData()
    }


    override fun initListener() {
        mAdapter.setOnItemClickListener { _, _, p ->
            startDetails(mAdapter.getItem(p))
        }
        findViewById<View>(R.id.m_back_icon).setOnClickListener { finish() }
    }


}